<?php
namespace app\Home\controller;
use \think\Controller;
use think\Db;
use think\Session;
use think\Cache;
use think\Request;

//定义常量
define('PATH', 'D:/wwwroot/apizgyejynet_2bacea/web/public');


class Home extends Controller
{

	public $phoneCode;
	/**
	* 按json方式输出通信数据
	* $code 状态码
	* $message 提示信息
	* $data 数据
	* return string 
	*/
	public static function json($code,$message = '', $data = array())
	{
		//判断状态码是否正确
		if(!is_numeric($code)){
			return '';
		}
		//拼接数组
		$result = array(
			'code'=>$code,
			'message'=>$message,
			'data'=>$data
		);
		//转换成json格式
		echo json_encode($result);
	}


	/**
	** 注册
	**/
	public function register()
	{
		$post = input('post.');
		$phone = isset($post['phone']) ? $post['phone'] : '';
		$password = isset($post['password']) ? $post['password'] : '';
		$phoneCode = $post['phoneCode'];
		//判断		
		if(!empty($phone) && !empty($password) && !empty($phoneCode)){
			//查找phoneCode
			$Code = Db('phonecode')->where('phone',$phone)->order('id desc')->find();
			if($phoneCode == $Code['phoneCode']){
				//查询
				$res = Db('users')->where('phone',$phone)->find();
				//
				if(empty($res)){
						$data['phone'] = $phone;
						$data['password'] = md5($password);
						$data['integralcount'] = 0;
						$data['jingyan'] = 0;
						$data['num'] = 0;
						$data['addtime'] = time();
						//制作token值
						$str = str_shuffle('1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$%*');
						$data['token'] = substr($str,rand(1,20),20);

						$id = Db::name('users')->insertGetId($data);
						// $id = Db('users')->where('token',$data['token'])->find();

					    $data2 = array(
			                'uid' => $id,
			                 'nickname' => 'zgyejy'.$data['phone']
			                );
							 $userInfo= Db('userinfo')->insert($data2);
						if($userInfo == 1){
							//删除严正吗
							Db('phonecode')->where('phone',$phone)->delete();


							return self::json(200,'注册成功');
							
						}else{
							return self::json(400,'注册失败',null);
						}
				}else{
					return self::json(402,'手机号已注册',null);
				}
			}else{
				return self::json(401,'验证码不正确',null);
			}
		}else{
			if(empty($phone)){
				return self::json(403,'手机号不能为空',null);
			}
			if(empty($password)){
				return self::json(404,'，密码不能为空',null);
			}
			if(empty($phoneCode)){
				return self::json(405,'请输入短信验证码',null);
			}
		}

	}


	/**
	**短信验证
	**/
	public function phoneCode()
	{

		$phone = input('get.phone');
		if($phone){
			
				$code= Db('phonecode')->where('phone',$phone)->find();
				if($code){
					$time = time() - $code['addtime'];
					if($time > 120){
						$this->getPhoneCode($phone);
					}
				}else{
					$this->getPhoneCode($phone);
				}
			
		}
		
	}
	/**
	** 发送验证吗
	**/
	private function getPhoneCode($phone)
	{
		//短信验证的接口
		$target = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
		//需要发送的验证码
		$mobile_code = $this->random(4,1);
		//拼接url参数
		$post_data = "account=cf_1453820803&password=7720d84424ea77458823e2d6547a1652&mobile=".$phone."&content=".rawurlencode("您的验证码是：".$mobile_code."。请不要把验证码泄露给其他人。");
		$post = $this->Post($post_data, $target);
		$gets =  $this->xml_to_array($post);
		if($gets['SubmitResult']['code']==2){
			//删除原有的phoneCode
			$res = Db('phonecode')->where('phone',$phone)->delete();
			//存入数据库
			$data['phoneCode'] = $mobile_code;
			$data['phone'] = $phone;
			$data['addtime'] = time();
			Db('phonecode')->insert($data);
			return self::json(200,'提交成功');			
		}else{
			return self::json(400,'提交失败',null);
		}
	}

	private function Post($curlPost,$url){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_NOBODY, true);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
		$return_str = curl_exec($curl);
		curl_close($curl);
		return $return_str;
	}

	private function xml_to_array($xml){
		$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
		if(preg_match_all($reg, $xml, $matches)){
			$count = count($matches[0]);
			for($i = 0; $i < $count; $i++){
			$subxml= $matches[2][$i];
			$key = $matches[1][$i];
				if(preg_match( $reg, $subxml )){
					$arr[$key] = $this->xml_to_array( $subxml );
				}else{
					$arr[$key] = $subxml;
				}
			}
		}
		return $arr;
	}
	//制作验证码
	private function random($length = 6 , $numeric = 0) {
		PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
		if($numeric) {
			$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
		} else {
			$hash = '';
			$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
			$max = strlen($chars) - 1;
			for($i = 0; $i < $length; $i++) {
				$hash .= $chars[mt_rand(0, $max)];
			}
		}
		return $hash;
	}


	/**
	*	登录
	**/
	public function login()
	{
		//定义空数组
		$data = array();
		//获取数据
		$post = input('post.');
		//查询用户信息
		$user = Db('users')->where('phone',$post['phone'])->find();
		//判断手机号是否被注册
		if(!empty($user)){
			//判断密码是否正确
			if($user['password'] == md5($post['password'])){

				$data['token'] = $user['token'];
				return self::json(200,'登录成功',$data);
				
			}else{
				return self::json(400,'密码不正确',null);
			}
		}else{
			return self::json(403,'用户名不存在',null);
		}
	}

	/**
	** 忘记密码
	**/
	public function forgetPassword()
	{
		$phone = input('post.phone');
		if(!empty($phone)){
			$res = Db('users')->where('phone',$phone)->find();
			if(!empty($res)){
				$this->getPhoneCode($phone);
			}else{
				return self::json(404,'手机号未注册',null);
			}
		}else{
			return self::json(400,'未传入手机号',null);
		}
	}
	/**
	**修改密码
	**/
	public function EditPassword()
	{
		$phone = input('post.phone');
		$password = input('post.password');
		$phoneCode = input('post.phoneCode');
		if(!empty($phone) && !empty($password)){
			$Code = Db('phonecode')->where('phone',$phone)->order('id desc')->find();
			if($phoneCode == $Code['phoneCode'] ){
				$data['password'] = md5($password);
				$res = Db('users')->where('phone',$phone)->update($data);
				if($res == 1){
					//删除严正吗
					Db('phonecode')->where('phone',$phone)->delete();
					return self::json(200,'密码重置成功');

				}else{
					return self::json(202,'密码重置失败',null);
				}
			}else{
				return self::json(400,'验证码不正确',null);
			}
		}else{
			if(empty($phone)){
				return self::json(401,'手机号不能为空',null);
			}
			if(empty($password)){
				return self::json(402,'密码不能为空',null);
			}
			if(empty($phoneCode)){
				return self::json(403,'验证码不能为空',null);
			}
		}
	}

	/**
	** 视频的详细信息
	**/
	public function videoinfo()
	{
		//定义空数组
		$data = array();
		//获取数据
		$get = input('get.');
		//查询用户信息
		$user = Db('users')->where('token',$get['token'])->find();
		//查询视频信息
		$video = Db('video')->where('id',$get['id'])->find();
		//需要返回的数据
		// $video['video_zip']='1123aaaaaa';

		$data['video']['video_name'] = $video['video_name'];
		$data['video']['video_zip'] = 'http://api.zgyejy.net'.$video['video_zip'];
		$data['video']['video_addtime'] = $video['video_addtime'];
		$data['video']['video_url'] = 'http://api.zgyejy.net'.$video['video_url'];
		$data['video']['see_num'] = $video['see_num'];
		$data['video']['evaluate_num'] = $video['evaluate_num'];
		$data['video']['collect_num'] = $video['collect_num'];
		$data['video']['video_style'] = $video['video_style'];
		//查mp3和文档
		$mp3Text = Db('mp3text')->where('cateId',$video['cate_id'])->find();
		if(!empty($mp3Text)){
			$data['music']['music_url'] = 'http://api.zgyejy.net'.$mp3Text['music'];
			$data['music']['music_name'] = $mp3Text['music_name'];
			$data['text']['text_url'] = 'http://api.zgyejy.net'.$mp3Text['text'];
			$data['text']['text_name'] = $mp3Text['text_name'];
		}
		//判断视频是否付费
		if($video['video_style'] == 2 || $video['video_style'] == 3 ){
			//查询付费表
			$payVideo = Db('payvideo')->where('userid',$user['id'])->find();
			//判断该用户是否付费
			if($payvideo['vid'] == $video['id']){
				self::json(200,'视频详情页数据获取成功',$data);
			}else{
				self::json(403,'用户未付费',null);
			}
		}else{
			self::json(200,'视频详情页数据获取成功',$data);
		}

	}
	
	/**
	** 视频列表页
	**/
	public function videoList()
	{
		//接收分页参数
		$get = input('get.');
		$token = input('get.token');
		$status = Db('users')->where('token',$token)->value('status');
		if($status == 1){
			return self::json(300,'你被列入黑名单，暂无法访问');
		}
		//判断是否有分页参数
		$page = isset($get['page']) ? $get['page'] : 1;
		$pageSize = isset($get['pageSize']) ? $get['pageSize'] : 6;
		//判断是否收费
		$videoStyle = isset($get['videoStyle']) ? $get['videoStyle'] : '';
		//判断其他类型的视频
		// $collectVideo = isset($get['collectVideo']) ? $get['collectVideo'] : '';
		// $payVideo = isset($get['payVideo']) ? $get['payVideo'] : '';
		//判断分页数据是否合法
		if(!is_numeric($page) || !is_numeric($pageSize)){
			return self::json(401,'分页数据不合法',null);
		}
		//	
		$offset = ($page - 1) * $pageSize;
		//判断
		// if(empty($videoStyle)){
		// 	//查询数据库
		// 	$videos = Db('video')
		// 			->order('id desc')
		// 			->limit($offset,$pageSize)
		// 			->select();
		// }
		if(!empty($videoStyle)){
			//判断视频类型数据是否合法
			if(is_numeric($videoStyle)){
				if($videoStyle == 1 || $videoStyle == 2 || $videoStyle == 3){
					//查询付费或免费视频
					$videos = Db('video')
							->where('video_style',$videoStyle)
							->order('id desc')
							->limit($offset,$pageSize)
							->select();
					foreach($videos as $k => $v){
						$videos[$k] = $v['id'];
					}			
					
				}elseif($videoStyle == 4){
					//查询收藏视频
					$user = Db('users')
							->where('token',$token)
							->find();
					//查询视频收藏表
					$collect = Db('collectvideo')
							->where('userid',$user['id'])
							->select();
					//查询视频的信息
					$videos = array();
					foreach($collect as $k => $v){
						$videos[$k] = $v['vid'];
					}
					// foreach($collect as $k => $v){
					// 	 $video = $this->getVideoById($v['vid']);
					// 	 $videos[$k] = $video;
					// }
				}else{
					return self::json(401,'视频是否付费数据不合法',null);
				}							
			}else{
					return self::json(401,'视频是否付费数据不合法',null);
			}
		}
		// elseif(!empty($collectVideo)){
		// 	//判断收藏视频的参数是否合法
		// 	if($collectVideo == 'collectVideo'){
		// 		//查询用户数据库
		// 		$user = Db('users')
		// 				->where('token',Session::get('token'))
		// 				->find();
		// 		//查询视频收藏表
		// 		$collect = Db('collectvideo')
		// 				->where('userid',$user['id'])
		// 				->select();
		// 		//查询视频的信息
		// 		foreach($collect as $k => $v){
		// 			 $video = $this->getVideoById($v['vid']);
		// 			 $videos[$k] = $video;
		// 		}
		// 	}else{
		// 		return self::json(401,'收藏视频数据不合法');
		// 	}
			
		// }elseif(!empty($payVideo)){
		// 	//判断付费视频的参数是否合法
		// 	if($payVideo == 'payVideo'){
		// 		//查询用户数据库
		// 		$user = Db('users')
		// 				->where('token',Session::get('token'))
		// 				->find();
		// 		//查询付过费的视频表
		// 		$collect = Db('payvideo')
		// 				->where('userid',$user['id'])
		// 				->select();
		// 		////查询视频的信息
		// 		foreach($collect as $k => $v){
		// 			 $video = $this->getVideoById($v['vid']);
		// 			 $videos[$k] = $video;
		// 		}
			// }else{
			// 	return self::json(401,'付费视频数据不合法','null');
			// }
			
		// }	
		//判断
		if($videos){
			return self::json(200,'视频列表页数据获取成功',$videos);
		}else{
			return self::json(400,'暂无视频列表页数据',null);
		}
	}

		/**
	**视频的收藏接口
	**/
	public function videoCollect()
	{
		$id = input('get.id');
		$token = input('get.token');
		if($id || $token){
			if(is_numeric($id)){
				$user = Db('users')->where('token',$token)->find();
				$data['userid'] = $user['id'];
				$data['vid'] = $id;
				$res = Db('collectvideo')->insert($data);
				if($res == 1){
					return self::json(200,'收藏视频成功',null);
				}else{
					return self::json(404,'视频收藏失败',null);
				}
			}else{
				return self::json(403,'视频的id值不合法',null);
			}
		}else{
			return self::json(400,'为传入视频的id或用户的token',null);
		}
	}

	/**
	* 通过id获取视频的信息
	*/
	private function getVideoById($id)
	{
		//读取数据库
		$videoInfo = Db::table('video') -> where('id','=',$id) ->find();
		//返回名称
		return $videoInfo;
	}


	/**
	** 添加个人中心接口
	**/
	// public function addUserInfo()
	// {
	// 	$token = input('get.token');
	// 	if($token){
	// 		$username = input('post.username');
	// 		$email =input('post.email');
	// 		$image = request()->file('image');
	// 		if(!empty($image)){
	// 			$image = $this->uploadimg($image);
	//             $data['image'] = $image;
	// 		}
	// 		$data['email'] = $email;
	// 		$data['username'] = $username;
	// 		$res = Db('users')->where('token',$token)->update($data);
	// 		if($res ==1){
	// 			return self::json(200,'添加成功');
	// 		}else{
	// 			return self::json(300,'添加失败',null);
	// 		}
	// 	}else{
	// 		return self::json(400,'没有传入token',null);
	// 	}
		
	// }
	/**
	**加添个人信息
	**/ 
 	// public function ziliao()
 	// {
 	// 	$token = input('get.token');
 	// 	$id = input('get.id');
 	// 	if($token && $id){
 	// 		$nickname = input('post.nickname');
		// 	$data['nickname'] = $nickname;
 	// 		$gender = input('post.gender');
		// 	$data['gender'] = $gender;
 	// 		$identity = input('post.identity');
		// 	$data['identity'] = $identity;
 	// 		$qq = input('post.qq');
		// 	$data['qq'] = $qq;

 	// 		$weichat = input('post.weichat');
		// 	if(!empty($weichat)){
		// 		$data['weichat'] = $weichat;
		// 	}
 	// 		$kindergarten = input('post.kindergarten');
		// 	if(!empty($kindergarten)){
		// 		$data['kindergarten'] = $kindergarten;
		// 	}
 	// 		$email = input('post.email');
		// 	if(!empty($email)){
		// 		$data['email'] = $email;
		// 	}
 	// 		$signature = input('post.signature');
		// 	if(!empty($signature)){
		// 		$data['signature'] = $signature;
		// 	}

		// 	$users = Db('users')->find();
		// 	$users = $users['id'];

		// 	$tokens = Db('userinfo')->find();
		// 	$tokens=$tokens['token'];
		// 	if($id == $users && $token == $tokens){
		// 		$res = Db('userinfo')->where('token',$token)->update($data);
		// 	}else{
		// 		$data['uid'] = $id;
		// 		$data['token'] = $token;
		// 		$res = Db('userinfo')->insert($data);
		// 	}

		// 	if($res ==1){
		// 		return self::json(200,'添加成功',$data);
		// 	}else{
		// 		return self::json(200,'更新成功',$data);
		// 	}
		// }else{
		// 	return self::json(400,'没有传入token',null);
		// }
 	// }
 	/**
	** 添加个人中心接口
	**/
	public function addUserInfo()
	{
		$token = Request::instance()->get('token');
		if($token){
			//昵称
			$nickname = input('get.nickname');
	    	if(!$nickname){
	    		return self::json(401,'未传入nickname');
	    	}
	    	//图片id
 			$iid = input('get.iid');
	    	if(!$iid){
	    		return self::json(405,'未传入图片ID');
	    	}else{
	    		// $userID = $this->getUid($token);
	    		// var_dump($userID);die;
	    		$icon = Db('icon')->where('id',$iid)->value('id');

	    		// $icon = Db('icon')->where('id',$userID)->find();
	    		// var_dump($icon['id']);die;

	    		// var_dump($data['iid']);die;
	    	}

	    	$userID = $this->getUid($token);

    		$userId = Db('users')->where('token',$token)->value('id');
    		// var_dump($userId);
			$data['uid'] =$userId;
    		// var_dump($data['uid']);die;
			//性别
 			$gender = input('post.gender');
			if(!empty($gender)){
				$data['gender'] = $gender;
			}
			//身份
 			$identity = input('post.identity');
			if(!empty($identity)){
				$data['identity'] = $identity;
			}
			//qq
 			$qq = input('post.qq');
			if(!empty($qq)){
				$data['qq'] = $qq;
			}
			//微信
 			$weichat = input('post.weichat');
			if(!empty($weichat)){
				$data['weichat'] = $weichat;
			}
			//头像
			// $image = request()->file('image');
			// if(!empty($image)){
			// 	$image = $this->uploadimg($image);
	  //           $data['image'] = $image;
			// }

			//幼儿园
 			$kindergarten = input('post.kindergarten');
			if(!empty($kindergarten)){
				$data['kindergarten'] = $kindergarten;
			}
			//邮箱
 			$email = input('post.email');
			if(!empty($email)){
				$data['email'] = $email;
			}
			//个性签名
 			$signature = input('post.signature');
			if(!empty($signature)){
				$data['signature'] = $signature;
			}
			$data['iid'] = $icon;
			// var_dump($data['iid']);die;
			$data['nickname'] = $nickname;
			// $data['gender'] = $gender;
			// $data['identity'] = $identity;
			// $data['qq'] = $qq;
			// $userinfoID =Db('userinfo')
			if(empty($userID)){
				$res = Db('userinfo')->insert($data);
			}else{

				$res = Db('userinfo')->where('uid',$userID)->update($data);
			}

			if($res ==1){
				return self::json(200,'添加成功',$data);
			}else{
				return self::json(300,'添加失败',null);
			}
		}else{
			return self::json(400,'没有传入token',null);
		}
	}
	/**
    *   编辑个人信息
    **/
	public function editUserInfo()
	{
		$token = Request::instance()->get('token');
		// var_dump($token);die;
		$data = [];
		// var_dump($token);
		if($token){
    		$userID = $this->getUid($token);	
			// var_dump($userID);die;
			// var_dump($res);die;
 			$nickname = Request::instance()->post('nickname');
 			// var_dump($nickname);die;
 			$gender = Request::instance()->post('gender');
 			$identity = Request::instance()->post('identity');
 			$qq = Request::instance()->post('qq');
 			$weichat = Request::instance()->post('weichat');
			// $image = request()->file('image');
			$iid = Request::instance()->post('iid');
 			$kindergarten = Request::instance()->post('kindergarten');
 			$email = Request::instance()->post('email');
 			$signature = Request::instance()->post('signature');

 			$info= Db('userinfo')->where('uid',$userID)->find();
 			if($info['nickname'] != $nickname ){
				//昵称
				if(!empty($nickname)){
					$data['nickname'] = $nickname;
				}
 			}
 			if($info['gender'] != $gender ){
				//性别
				if(!empty($gender)){
					$data['gender'] = $gender;
				}
 			}
 			if($info['identity'] != $identity){
				//身份
				if(!empty($identity)){
					$data['identity'] = $identity;
				}
 			}
 			if($info['qq'] != $qq){
				//qq
				if(!empty($qq)){
					$data['qq'] = $qq;
				}
 			}
 			if($info['weichat'] != $weichat){
				//微信
				if(!empty($weichat)){
					$data['weichat'] = $weichat;
				}
 			}
 			if($info['iid'] != $iid){
				//头像1-24
				if(!empty($iid)){
 		            $data['iid'] = $iid;
				}
 			}
 			if($info['kindergarten'] != $kindergarten){
				//幼儿园
				if(!empty($kindergarten)){
					$data['kindergarten'] = $kindergarten;
				}
 			}
 			if($info['email'] != $email){
				//邮箱
				if(!empty($email)){
					$data['email'] = $email;
				}
 			}
 			if($info['signature'] != $signature){
				//个性签名
				if(!empty($signature)){
					$data['signature'] = $signature;
				}
 			}	

			$res = Db('userinfo')->where('uid',$userID)->update($data);
			// var_dump($res);die;
			if($res ==1){
				return self::json(200,'编辑成功',$data);
			}else{
				return self::json(300,'编辑失败');
			}
		}else{
			return self::json(400,'没有传入token');
		}	
	}
	/**
    *   查询个人信息接口
    **/
	public function showUserInfo()
	{
		$token = input('get.token');
		// var_dump($token);
		if(!$token){
			return self::json(400,'未传入token');
		}

    	$userID = $this->getUid($token);	

    	$iid = Db('userinfo')->where('uid',$userID)->value('iid');

    	$data['iconUrl'] = Db('icon')->where('id',$iid)->value('url');

    	$data['userinfo'] = Db('userinfo')->field('uid','nickname')->where('uid',$userID)->select();

   //  	$data = Db::field('icon.url,userinfo.nickname')
			// ->table('userinfo a,icon b')
			// ->limit(10)->select();
    	if(!$data){

    		return self::json(401,'没有此用户');
    	}else{

    		return self::json(200,'查询成功',$data);
    	}
	}

	/**
    *   点赞接口
    **/
    public function praise()
    {
    	$id = input('get.id');
    	$token = input('get.token');
    	if(!$id){
    		return self::json(401,'未传视频id');
    	}
    	if(!$token){
    		return self::json(402,'未传视频token');
    	}
    	$userId = Db('users')->where('token',$token)->value('id');
    	if($userId){
    		$praise = Db('praise')->where('uid',$userId)->where('vid',$id)->find();
    		if(!$praise){
    			$data = array(
	    			'uid' => $userId,
	    			'vid' => $id
	    			);
	    		$res = Db('praise')->insert($data);
	    		if($res == 1){
	    			return self::json(200,'点赞成功');
	    		}else{
	    			return self::json(400,'点赞失败');
	    		}
    		}else{
    			return self::json(403,'已点赞');
    		}
    	}else{
    		return self::json(300,'该用户不存在');
    	}
	}

	/**
    *   视频付积分接口
    **/
	public function payVideo()
	{
		$token = Request::instance()->get('token');
		$videoId = Request::instance()->get('id');
		if(!$token){
			return self::json(400,'未传token');
		}
		if(!$videoId){
			return self::json(401,'未传视频id');
		}
		$video_jifen= Db('video')->where('id',$videoId)->value('video_jifen');

		$userId = Db('users')->where('token',$token)->find();

		if($userId){
			$res = Db('payvideo')->where('vid',$videoId)->where('userid',$userId['id'])->find();
			// var_dump($res);die();
			if(!empty($res)){
				return self::json(301,'该视频已购买');
			}else{
				if((int)$userId['integralcount'] >= (int)$video_jifen){
					//余额
					// var_dump((int)$userId['integralcount']);
					// var_dump((int)$video_jifen);die;
					$balance = (int)$userId['integralcount'] - (int)$video_jifen;
					// var_dump($balance);die();
						//插入余额
	    				$data2 = array(
	    				'integralcount'=>(int)$balance
	    				);
					Db('users')->where('id',$userId['id'])->update($data2);	
					//插入payvideo表中视频id和用户id 
	    				$data = array(
	    				'vid'=>$videoId,
	    				'userid'=>$userId['id']
	    				);
					$access = Db('payvideo')->where('vid',$videoId)->where('userid',$userId['id'])->insert($data);
					return self::json(200,'购买成功',$access);
				}else{
					return self::json(402,'积分不足');
				}
			}

		}else{
			return self::json(300,'该用户不存在');
		}
	}

	/**
    *   视频评星接口
    **/
    public function rating()
    {
    	$id = input('get.id');
    	$token = input('get.token');
		$star = input('post.star');
    	if(!$id){
    		return self::json(401,'未传视频id');
    	}
    	if(!$token){
    		return self::json(402,'未传token');
    	}
    	if(!$star){
    		return self::json(404,'未传评星值');
    	}
    	$userId = Db('users')->where('token',$token)->value('id');
    	// var_dump($userId);die;
    	if($userId){
    		$rating= Db('rating')->where('uid',$userId)->where('vid',$id)->find();
    		if(!$rating){
    			$data = array(
    				'uid'=>$userId,
    				'vid'=>$id,
    				'star'=>$star
    				);
    			$res = Db('rating')->insert($data);
    			if($res == 1){
                    return self::json(200,'评星成功');
    			}else{
                    return self::json(400,'评星失败');
    			}	
    		}else{
                return self::json(403,'已评论');
    		}
    	}else{
            return self::json(300,'该用户不存在');
    	}
    }	

	/**
    *   浏览次数接口
    **/
	public function see()
	{	
		//视频id
		$id = input('get.id');
		//目录id
		$cid = input('get.cid');
		
		if(!$id){
			return self::json(400,'未传入id');
		}
		if(!$cid){
			return self::json(401,'未传入目录id');
		}
		if(is_numeric($id)){
			$cateID = Db('video')->where('id',$id)->value('cate_id');
		}else{
			return self::json(403,'视频的id值不合法');
		}
		//判断传来的id和数据库查到的id是否相等
		if($cateID == $cid){
			$vid = Db('video')->where('id',$id)->value('see_num');
			// $vid =(int)$vid;
			$data['see_num']=$vid+1;
	        $res = Db('video')->where('id',$id)->update($data);
	        return self::json(200,'浏览成功');
		}else{
			return self::json(402,'目录id不存在');
		}
	}
 
 	/**
    *   秀一秀发表
    **/
   	public function show()
   	{
   		$id = input('get.id');

   		if($id){
   			//视频
 			$video = request()->file('video');
			if(!empty($video)){
				$video = uploadvideo($video);
				$data['video'] = $video;
			}
			//照片
			$image = request()->file('image');
			if(!empty($image)){
				$image = uploadimg($image);
	            $data['image'] = $image;
			}
			//文本
 			$text = request()->file('text');
			if(!empty($text)){
				$text = uploadtext($text);
				$data['text'] = $text;
			}
			//文字
 			$word = input('post.word');
 			if(!$word){
    			return self::json(401,'未传入文字');
 			}
			$data['word'] = $word;

			//音乐
 			$music = request()->file('music');
			if(!empty($music)){
				$music = uploadmusic($music);
				$data['music'] = $music;
			}
    		$userId = Db('users')->value('id');
			$data['uid'] =$userId;
			$data['time']=time();
    		// var_dump($data['uid']);
			$res = Db('shows')->insert($data);

			if($res == 1){
    			return self::json(200,'发表成功');
    		}else{
    			return self::json(300,'发表失败');
    		}

   		}else{
			return self::json(400,'没有传入id');

   		}
   	}

   	//获取getUid
	private function getUid($token){
		$userID = Db('users')->where('token',$token)->value('id');
		return $userID;

	}
	/**
    *   查看秀一秀接口
    **/
    public function look()
    {
    	$token = input('get.token');
    	// var_dump($token);
    	if(!$token){
    		return self::json(401,'未传token');
    	}	

    	$userID = $this->getUid($token);	
    	// var_dump($userID);die;
    	$data = Db('shows')->where('uid',$userID)->order('id desc')->find();
    	if(!$data){
    		return self::json(400,'没有此用户');
    	}else{

    		return self::json(200,'查询成功',$data);
    	}
    }
	/**
    *   图片上传操作
    **/
    private function uploadimg($image)
    {
        // 获取表单上传文件 例如上传了001.jpg
        // $img = request()->file('video_zip');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $imginfo = $image->move(ROOT_PATH . 'public' . DS . 'uploads'. DS .'users'. DS .'images');
        //
        if($imginfo){
                return $url = "/uploads/users/images/20".date("ymd",time())."/".$imginfo->getBasename();
        }else{
            // 上传失败获取错误信息
            return  $image->getError();
        }   
    }

    private function getIconId($token){
		$userID = Db('users')->where('token',$token)->value('id');
    	$userInfoIid = Db('userinfo')->where('uid',$userID)->value('iid');
		return $userInfoIid;

    }

	/***
	**	个人中心接口
	**/
	public function userInfo()
	{
		$token = input('get.token');

		//查询
		$userInfo = Db('users')
					->where('token',$token)
					->find();
		// var_dump($userInfo);

		$user = Db('userinfo')->where('uid',$userInfo['id'])->find();
    	
    	$iconID = $this->getIconId($token);

    	$iconUrl = Db('icon')->where('id',$iconID)->value('url');



		// var_dump($iconUrl);die;
		// $icon = Db('icon')->where('iid',$userInfo['id'])->find(); 
		// var_dump($icon);die;

		$data['nickname'] = $user['nickname'];
		// $data['image'] = 'http://api.zgyejy.net'.$user['image'];
		$data['image'] = $iconUrl;
		// var_dump($data['image']);

		
		// $data['nickname'] = $userInfo['nickname'];
		// $data['image'] ='http://api.zgyejy.net'.$userInfo['image'];
		$data['integralcount'] = $userInfo['integralcount'];
		//付费视频列表
		$payvideo = Db('payvideo')->where('userid',$userInfo['id'])->select();
			//查询视频的信息
		$payvideoId = array();
		//
		if($payvideo){
			foreach($payvideo as $k => $v){
				 $payvideoId[$k] = $v['vid'];
				}
		}
		$data['payVideo'] = $payvideoId;
		//收藏视频列表
		$collectVideo = Db('collectvideo')->where('userid',$userInfo['id'])->select();
		//查询视频的信息
		$collectvideoId = array();
		if($collectVideo){
			foreach($collectVideo as $k => $v){
				 $collectvideoId[$k] = $v['vid'];
			}
		}			
		$data['collectVideo'] = $collectvideoId;
		//优惠券
		$data['coupon'] = Db('coupon')->where('userid',$userInfo['id'])->field('addtime,endtime,content')->select();
		
		//判断
		if($data){
			return self::json(200,'个人中心数据获取成功',$data);
		}else{
			return self::json(400,'个人中心数据获取失败',null);
		}

	}

	/**
	*	评论接口
	**/
	public function comment()
	{
		//传入视频的id
		$get= input('get.');
		$videoId = isset($get['id']) ? $get['id'] : '';
		//传入用户的token 评论content
		$post  = input('post.content');
		$token = input('get.token');
		$token = isset($token) ? $token : '';
		$content = isset($post) ? $post : '';
		//判断video的id是否存在
		if($videoId){
			//id是否合法
			if(is_numeric($videoId)){
				//查询video数据
				$video = Db('video')->where('id',$videoId)->find();

				//判断是输出评论还是插入评论
				if(!empty($token) && !empty($content)){
					//插入评论内容
					$user = Db('users')->where('token',$token)->find();
					$data['phone'] = $user['phone'];
					$data['videoName']= $video['video_name'];
					$data['addtime'] = time();
					$data['status'] = 0;
					$data['content'] = $content;
					$res = Db('comment')->insert($data);
					if($res == 1){
						return self::json(200,'评论成功');
					}else{
						return self::json(400,'评论失败',null);
					}
				}elseif(empty($token) && empty($content)){
					//查询评论表
					$comment = Db('comment')->where('videoName',$video['video_name'])->select();
					//查询头像
					// $icon = Db('')
					//查询用户表
					$data = array();
					foreach ($comment as $k => $v){

						$data[$k]['userImage'] = $this->getUserById2($v['phone']);
						// $data[$k]['userImage'] = $this->getUserById2($phone);
						// var_dump($data[$k]['userImage']);die;
						$data[$k]['phone'] = $comment[$k]['phone'];
						$data[$k]['content'] = $comment[$k]['content'];
						$data[$k]['addtime'] = $comment[$k]['addtime'];
					}				
					return self::json(200,'返回评论信息成功',$data);	
				}

			}else{
				return self::json(401,'视频的id值不合法',null);
			}			
		}

		
	}

	/**
	* 通过id获取用户的信息
	*/
	private function getUserById($phone)
	{
		//读取数据库
		$userInfo = Db('users') -> where('phone',$phone) ->find();
		//返回名称
		return $userInfo['image'];
	}


	/**
	* 通过手机号码获取头像url
	*/
	private function getUserById2($phone)
	{
		//读取数据库
		$userId = Db('users')->where('phone',$phone)->value('id');
		$iid = Db('userinfo') ->where('uid',$userId)->value('iid');
		$userInfo = Db('icon')->where('id',$iid)->value('url');

		//返回名称
		return $userInfo;
	}

	/**
	**	活动推送的接口
	**/
	public function actives()
	{
		//已结束的活动
		$endActive = Db('active')
				->where('active_endtime','<',time())
				->order('id desc')
				->select();
		//正在开始的活动
		$nowActive = Db('active')
				->where('active_begintime','<=',time())
				->where('active_endtime','>=',time())
				->order('id desc')
				->select();
		//还未开始的活动
		$laterActive = Db('active')
				->where('active_begintime','>',time())
				->order('id desc')
				->select();
		$actives['end'] = $endActive;
		$actives['now'] = $nowActive;
		$actives['later'] = $laterActive;
		if(!empty($actives)){
			return self::json(200,'返回活动信息成功',$actives);
		}else{
			return self::json(400,'返回活动信息失败',$actives);
		}
		
	}


		/**
	* 积分系统接口
	**/
	public function integral()
	{
		$flag = Request::instance()->get('flag');
		$token = Request::instance()->get('token');
		$token = isset($token) ? $token : '';
		$flag = isset($flag) ? $flag : '';
		//
		if(!empty($flag)){
			//
			if(!is_numeric($flag)){
				return self::json(400,'数据不合法',null);
			}
			if($flag == 1){
				    $phone = Db('users')->where('token',$token)->value('phone');
					$integral_log = Db('integral_log')
					->where('phone',$phone)
					->where('flag',$flag)
					->order('addtime desc')
					->find();
					if(empty($integral_log)){
						$this->integralAdd($flag,$token);
					}else{
						$time = $integral_log['addtime'];
						// var_dump($time);
						//获取当前时间
						$nowTime = date('Y-m-d',time());
						// var_dump($nowTime);die;

						//今天开始的时间
						$beginTime = strtotime($nowTime.'00:00:00');
						// var_dump($beginTime);

						//今天结束的时间
						$endTime = strtotime($nowTime.'24:00:00');
						// var_dump($endTime);die;

						if($beginTime <= $time && $time <= $endTime){
							return self::json(300,'今日已领取积分',null);
						}elseif($beginTime > $time ){
							$this->integralAdd($flag,$token);
						}
					}
			}elseif($flag == 2){
					$this->integralAdd($flag,$token);
			}								
		}else{
			return self::json(404,'传入参数为空',null);
		}		
	}

	/**
	** 添加积分日至操作
	**/
	private function integralAdd($flag,$token)
	{
			$coupon = Db('integral')->where('flag',$flag)->find();
			//查询当前用户
			
			$user = Db('users')
					->where('token',$token)
					->find();	
			
			if(empty($user)){
				return self::json(402,'用户不存在');
			}			
			//增加积分
			$user['integralcount'] += $coupon['value'];
			$data['integralcount'] = $user['integralcount'];		
			$res = Db('users')
					->where('token',$token)
					->update($data);
			//判断是否添加成功
			if($res == 1){
				$datas['phone'] = $user['phone'];
				$datas['addtime']  = time();
				$datas['addnum'] = $coupon['value'];
				$datas['flag'] = $flag;
				$result = Db('integral_log')->insert($datas);
				if($result == 1){
					return self::json(200,'添加积分成功');
				}else{
					return self::json(400,'写入积分日志失败');
				}
			}else{
				return self::json(401,'积分添加失败');
			}
	}

	/**
	**版本升级接口
	**/
	public function version()
	{
		//接受信息
		$post = (input('post.'));	
		$app = isset($post['app']) ? $post['app'] : '';
		$versionCode = isset($post['versionCode']) ? $post['versionCode'] : '';
		if(!empty($app) && !empty($versionCode)){
				//判断客户端是什么类型的
				$appId = $this->getApp($app);
				//查询最新版本的
				$version = Db('version_upgrade')->where('app_id',$appId)->order('id desc')->find();
				
				//判断是否更新
			
				if($version['version_code'] > $versionCode){
					$data['versionUrl'] = $version['version_url'];
					 if($version['type'] == 1){
					 	return self::json(400,'暂不更新',null);
					 }elseif($version['type'] == 2){
					 	return self::json(200,'非强制更新',$data);
					 }elseif($version['type'] == 3){
					 	return self::json(201,'强制更新',$data);
					 }			 
				}elseif($version['version_code'] = $versionCode){
					return self::json(401,'最新版本，不需更新',null);
				}elseif($version['version_code'] < $versionCode){
					return self::json(402,'版本号不合法',null);
				}
		}else{
			if(empty($app)){
				return self::json('404','客户端型号不能为空',null);
			}
			if(empty($versionCode)){
				return self::json('403','版本号不能为空',null);
			}
		}
		
	}

	/**
	**版本升级接口
	**/
	private function getApp($appInfo)
	{
		$app = Db('app')->where('app_info',$appInfo)->find();
		return $app['id'];
	}

	/**
	**活跃流
	**/
    public function liveing()
    {
        vendor('pili-sdk-php#v2-master.lib.Pili_v2');
        $ak = "3i3ZvMKt8vafh38cAH8E6X0a0YrtAtojszFRHRPj";
        $sk = "FI9b2f4DeHVRSYoHKihOSUp-Sj17S7C0w885nzY5";
        $hubName = "yudong";

		//创建hub
		$mac = new \Qiniu\Pili\Mac($ak, $sk);
		$client = new \Qiniu\Pili\Client($mac);
		$hub = $client->hub($hubName);
		//获取stream
		$streamKey = "php-sdk-test" . time();
		//活跃流
    	$liveing = $hub->listLiveStreams("php-sdk-test", 1, "");

    	$sign = empty($liveing['keys'])?true:false;
    	if($sign){
    		return self::json('300','没有正在直播的流',null);
    	}else{
    		
    		$data = array(
    			'liveing' => $liveing['keys'][0],
    			'pull_url' => \Qiniu\Pili\RTMPPlayURL("pili-live-rtmp.www.zgyejy.net", $hubName,$liveing['keys'][0]),
    			'hls_url' => \Qiniu\Pili\HLSPlayURL("pili-live-hls.www.zgyejy.net", $hubName,$liveing['keys'][0]),
    			'hdl_url' => \Qiniu\Pili\HDLPlayURL("pili-live-hdl.www.zgyejy.net", $hubName,$liveing['keys'][0]),
    			'icon_url'=> \Qiniu\Pili\SnapshotPlayURL("pili-live-snapshot.www.zgyejy.net", $hubName,$liveing['keys'][0])

    			);
    		// $data['liveing'] = $liveing['keys'][0];
    		return self::json('200','直播流',$data);
    	}
    }



}